package com.broheim.websocket.spring.processor;

import com.broheim.websocket.core.endpoint.server.WebSocketServer;
import com.broheim.websocket.core.listener.JsonMessageListener;
import com.broheim.websocket.spring.annonation.Command;
import com.broheim.websocket.spring.annonation.WebSocketController;
import com.broheim.websocket.spring.handler.HandlerRunnableInvoker;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.lang.reflect.Method;

public class JsonCommandListenerRegistryProcessor implements InitializingBean, ApplicationContextAware {

    private ApplicationContext applicationContext;


    @Override
    public void afterPropertiesSet() throws Exception {
        String[] webSocketControllerNames = applicationContext.getBeanNamesForAnnotation(WebSocketController.class);

        for (String webSocketControllerName : webSocketControllerNames) {
            Object bean = applicationContext.getBean(webSocketControllerName);
            WebSocketController annotation = bean.getClass().getAnnotation(WebSocketController.class);
            Method[] methods = bean.getClass().getDeclaredMethods();
            JsonMessageListener jsonMessageListener = new JsonMessageListener();
            for (Method method : methods) {
                Command command = method.getAnnotation(Command.class);
                if (null != command) {
                    HandlerRunnableInvoker handlerInvoker = HandlerRunnableInvoker.class.newInstance();
                    handlerInvoker.setObject(bean);
                    handlerInvoker.setMethod(method);
                    handlerInvoker.setArgTypes(method.getParameterTypes());
                    handlerInvoker.setCmd(command.value());
                    jsonMessageListener.register(command.value(), handlerInvoker);
                }
            }
            WebSocketServer.registerListener(annotation.value(), jsonMessageListener);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
